# -*- coding: utf-8 -*-
import hashlib
import json
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.channel.pay import check_channel_order
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError
from common.utils.ip_address import check_valid_ip_address

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '335': {
        #  乐联盟支付 支付宝 2.1% 100-10000 witch
        'API_KEY': 'cce4d1624b18d2aa75d0633bd6ea8624',
        'gateway': 'https://third.lepayunion.com/lepay/create_order',
        'query_gateway': 'https://third.lepayunion.com/lepay/query_order',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_app_id(mch_id):
    return APP_CONF[mch_id]['appId']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def _gen_sign(s):
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest()
    return sign


def generate_sign(parameter, key):
    s = ''
    for k in sorted(parameter.keys()):
        s += '%s' % parameter[k]
    s += '%s' % key
    return _gen_sign(s)


def gen_notify_sign(d, key):
    s = ''
    for k in sorted(d.keys()):
        s += '%s' % d[k]
    s += '%s' % key
    return _gen_sign(s)


def verify_notify_sign(params, key):
    sign = params['sign']
    params.pop('sign')
    calculated_sign = gen_notify_sign(params, key)
    if sign.upper() != calculated_sign.upper():
        _LOGGER.info("lelianmengpay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def create_charge(pay, pay_amount, info):
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('order_no', str(pay.id)),
        ('amount', str(int(pay_amount))),
        ('member_id', app_id),
        ('notify_url', '{}/pay/api/{}/lelianmengpay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('redirect_url',
         '{}/pay/api/{}/lelianmengpay/{}'.format(settings.NOTIFY_PREFIX, settings.RETURN_PATH, str(pay.id))),
        ('is_h5', '1'),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("lelianmengpay create: %s, order_id is: %s", json.dumps(parameter_dict), parameter_dict['order_no'])
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_gateway(app_id), data=parameter_dict, headers=headers, timeout=3)
    _LOGGER.info("lelianmengpay create rsp data: %s %s", response.status_code, response.text)
    return {'charge_info': json.loads(response.text)['pay_url']}


# success
def check_notify_sign(request, app_id):
    api_key = _get_api_key(app_id)
    data = dict(request.POST.iteritems())
    _LOGGER.info("lelianmengpay notify data: %s, order_id is: %s", data, data['order_no'])
    verify_notify_sign(data, api_key)
    pay_id = data['order_no']
    check_valid_ip_address(str(request.META['REMOTE_ADDR']), pay_id)
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s", data)
        raise ParamError('lelianmengpay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = str(data['order_status'])
    trade_no = str(data['union_order_no'])
    total_fee = float(data['amount'])
    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }
    check_channel_order(pay_id, total_fee, app_id)
    # 支付状态,1-交易完成
    if trade_status == '1':
        _LOGGER.info('lelianmengpay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    api_key = _get_api_key(app_id)
    p_dict = OrderedDict((
        ('order_no', pay_order.id),
        ('member_id', app_id),
    ))
    p_dict['sign'] = generate_sign(p_dict, api_key)
    _LOGGER.info('lelianmengpay query data: %s, order_id is: %s', json.dumps(p_dict), p_dict['order_no'])
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_query_gateway(app_id), data=p_dict, headers=headers, timeout=3)
    _LOGGER.info('lelianmengpay query, %s', response.text)
    if response.status_code == 200:
        data = json.loads(response.text)['info']
        mch_id = pay_order.mch_id
        trade_status = str(data['status'])
        total_fee = float(data['money'])
        trade_no = str(data['platform_order_no'])

        extend = {
            'trade_status': trade_status,
            'trade_no': trade_no,
            'total_fee': total_fee
        }

        if trade_status == '1' and total_fee > 0:
            _LOGGER.info('lelianmengpay query order success, mch_id:%s pay_id:%s' % (mch_id, pay_order.id))
            res = order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                           total_fee, trade_no, extend)
            if res:
                # async notify
                async_job.notify_mch(pay_order.id)
